package com.qianduo.struts.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.qianduo.service.impl.AccountServiceImpl;
import com.qianduo.struts.AbstractAction;
import com.qianduo.util.Constants;
import com.qianduo.vo.AccountForm;

import common.util.StringUtil;

public class LoginAction extends AbstractAction {	
	public ActionForward login(ActionMapping mapping,ActionForm form,HttpServletRequest req,HttpServletResponse res){
		List<String> errors = new ArrayList<String>();
		AccountForm qianduoAccountForm	= (AccountForm) form;
		if(StringUtil.isEmpty(qianduoAccountForm.getUsername())){
			errors.add("用户名不能为空");
		}
		if(StringUtil.isEmpty(qianduoAccountForm.getPassword())){
			errors.add("密码不能为空");
		}else{
			qianduoAccountForm.setPassword(StringUtil.encrypt(qianduoAccountForm.getPassword()));
		}
		if(StringUtil.isEmpty(qianduoAccountForm.getCheckcode())){
			errors.add("验证码不能为空");
		}
		if(errors.size() == 0){
			Object imageObj	= req.getSession(false).getAttribute(Constants.PICTURECODE);
			if(null != imageObj){
				String imageStr	= imageObj.toString();
				if(!imageStr.equalsIgnoreCase(qianduoAccountForm.getCheckcode())){
					errors.add("您输入的验证码不正确");
				}
			}
		}
		if(errors.size() == 0){
			AccountServiceImpl service		= (AccountServiceImpl)getBean("accountService");
			AccountForm	ret					= service.getQianduoAccount(qianduoAccountForm.getUsername(), qianduoAccountForm.getPassword());
			if(null != ret){				
				req.getSession(false).setAttribute(Constants.ACCOUNT, ret);
			}else{
				errors.add("您输入的用户名或密码错误");
			}
		}
		if(errors.size() == 0){
			return new ActionForward("qianduoAgency.do?action=listAgency",true);
		}else{
			req.setAttribute("errors", errors);
			return new ActionForward("/index.jsp");
		}
	}
	
	public ActionForward loginOut(ActionMapping mapping,ActionForm form,HttpServletRequest req,HttpServletResponse res){
		HttpSession session	= req.getSession(false);
		session.setAttribute(Constants.ACCOUNT,null);
		session.removeAttribute(Constants.ACCOUNT);
		return new ActionForward("/index.jsp");
	}
}